package com.zff.rental.common;

import com.zff.rental.utils.specification.SortBuilder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.List;

/**
 * 分页入参
 *
 * @author HCY
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class PageSortParams extends PageParams {
    /**
     * 排序方式
     */
    private List<SortParams> sort;

    /**
     * 生成查询数据库的Pageable
     */
    @Override
    public Pageable generatePageable() {
        Sort sortTem = generateSort(sort);
        if (sortTem == null) {
            return super.generatePageable();
        } else {
            return super.generatePageable(sortTem);
        }
    }

    public SortBuilder toSortBuilder() {
        SortBuilder sortBuilder = SortBuilder.builder();
        for (SortParams sortParams : sort) {
            if (sortParams.getIsDesc()) {
                sortBuilder.desc(sortParams.getProperty());
            } else {
                sortBuilder.asc(sortParams.getProperty());
            }
        }
        return sortBuilder;
    }

    /**
     * 包含属性
     */
    public boolean containsSort(String sortName) {
        if (sort != null && !sort.isEmpty()) {
            for (SortParams sortParams : sort) {
                if (sortName.equals(sortParams.getProperty())) {
                    return true;
                }
            }
        }
        return false;
    }
}
